package com.pengzy.comment.web.redis;

import com.pengzy.comment.web.exception.CustomException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * @author PC
 * @descripetion redis工具
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * redis分布式锁
     * @return
     */
    public boolean tryLock(String key, String value , long timeout) {
        if(timeout==0){
            timeout=60*3;
        }
        //设置过期时间,防止死锁
        /**
         * setIfAbsent就是setnx
         * 将key设置值为value，如果key不存在，这种情况下等同SET命令。
         * 当key存在时，什么也不做。SETNX是”SET if Not eXists”的简写
         * */
        boolean isSuccess=redisTemplate.opsForValue().setIfAbsent(key,value,timeout, TimeUnit.SECONDS);
        if(!isSuccess){
            System.out.println("锁被占用了");
           throw new CustomException("正在执行中，请别重复提交");
        }
        return isSuccess;
    }


    /**
     * Redis 分布式锁释放
     * @param key
     * @param value
     */
    public void unLock(String key, String value){
        try {
            String currentValue=(String) redisTemplate.opsForValue().get(key);
            if(StringUtils.isNotBlank(currentValue)&&StringUtils.equals(currentValue,value)){
                    redisTemplate.opsForValue().getOperations().delete(key);
            }
        }catch (Exception e){
            throw new RuntimeException("释放锁发生异常");
        }
    }





}
